package com.paomi.client.activity.onlineSeat;

import android.app.Activity;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.paomi.client.R;
import com.paomi.client.activity.detail.model.DetailTicketBean;
import com.paomi.client.activity.detail.model.PlanBean;
import com.paomi.client.activity.onlineSeat.model.SeatBean;
import com.paomi.client.activity.pay.PayActivity;
import com.paomi.client.base.BaseMvpActivity;
import com.paomi.client.fragment.first.model.BannerBean;
import com.paomi.client.net.Api;
import com.paomi.client.net.BaseCallback;
import com.paomi.client.net.Constants;
import com.paomi.client.utils.Datas;
import com.paomi.client.view.LoadingDialog;
import com.paomi.client.view.PopupWindowView;
import com.paomi.client.view.svg.MapView;
import com.paomi.client.widget.RxToast;

import org.json.JSONObject;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 在线选座页面
 */
public class OnlineSeatActivity extends BaseMvpActivity<OnlineMvpview, OnlinePresenter> implements PopupWindowView.OnDeleteClickListener {
    @BindView(R.id.svg_view)
    MapView svgView;
    @BindView(R.id.web_seat)
    WebView webSeat;
    @BindView(R.id.show_size)
    TextView showSize;
    @BindView(R.id.message_tv)
    TextView messageTv;
    @BindView(R.id.ticket_lay)
    RelativeLayout ticketLay;
    @BindView(R.id.choice_seat_button)
    Button choiceSeatButton;
    private DetailTicketBean.TicketBean ticketBean;//演出信息
    private PlanBean planBean;//选中的场次信息
    private List<SeatBean> seatData = new ArrayList<>();//座位信息数据
    private String urlGet;//得到的URL

    @NonNull
    @Override
    public OnlinePresenter createPresenter() {
        return new OnlinePresenter();
    }

    @Override
    protected String setTitle() {
        return getResources().getString(R.string.online_title);
    }

    @Override
    protected void showBack(TextView button_goback) {
        button_goback.setVisibility(View.VISIBLE);
        button_goback.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        button_goback.setTextColor(getResources().getColor(R.color.main_color));
        button_goback.setText(getResources().getString(R.string.back_normal) + "返回");
        button_goback.setTypeface(iconfont);

    }

    @NonNull
    @Override
    protected int getLayoutId() {
        return R.layout.activity_online_seat;
    }

    @JavascriptInterface
    @Override
    protected void initEvent() {
        ticketBean = (DetailTicketBean.TicketBean) getIntent().getSerializableExtra("detail");
        planBean = (PlanBean) getIntent().getSerializableExtra("plan");
//        getPresenter().getOnlinData("" + planBean.getGoodsId(), "" + planBean.getId());
//        webSeat.getSettings().setJavaScriptEnabled(true);
        // window 级 只能打开
        // 在5.0以上开启硬件加速器
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        }
        urlGet=Constants.HTML_SEAT_URL+getStringParams();
        webSeat.getSettings().setJavaScriptEnabled(true);
        webSeat.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webSeat.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSeat.getSettings().setUseWideViewPort(true);

        webSeat.getSettings().setLoadWithOverviewMode(true);
        webSeat.getSettings().setGeolocationEnabled(true);
        webSeat.getSettings().setDomStorageEnabled(true);
        //设置此属性，可任意比例缩放
//        webSeat.getSettings().setBuiltInZoomControls(true);
        webSeat.getSettings().setSupportZoom(true);
        webSeat.getSettings().setDisplayZoomControls(true);
        webSeat.getSettings().setUseWideViewPort(false); //将图片调整到适合webview的大小
        //显示滑动的滚动条
//        webViewone.getWebView().setHorizontalScrollBarEnabled(true);
//        webViewone.getWebView().setVerticalScrollBarEnabled(true);
//        webViewone.getWebView().setScrollContainer(true);
//        webViewone.getWebView().setInitialScale(70);
        webSeat.setHorizontalScrollBarEnabled(false);
        //listview,webview中滚动拖动到顶部或者底部时的阴影
        webSeat.setOverScrollMode(View.OVER_SCROLL_NEVER);
        //取消滚动条白边效果
        webSeat.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webSeat.setLayerType(View.LAYER_TYPE_SOFTWARE,null);
        webSeat.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();  // 接受所有网站的证书
                super.onReceivedSslError(view, handler, error);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //清除缓存的js
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        webSeat.loadUrl("javascript:window.localStorage.clear()");
//                    }
//                },100);
                webSeat.post(new Runnable() {
                    @Override
                    public void run() {
                        webSeat.loadUrl("javascript:window.localStorage.clear()");
                    }});
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Log.e("description",description+"---"+errorCode);
            }
        });
        webSeat.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                //对应js中的console.log方法,可以重写该方法完成与js的交互
//                        return super.onConsoleMessage(consoleMessage);
                return true;
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Log.e("main", "onJsAlert:" + message);

                //拦截弹出框中的数据
                SeatBean seatBean=Datas.fromJson(message,SeatBean.class);
                if(seatData.size()>0){//循环遍历去除重复数据
                    for(int i=0;i<seatData.size();i++){
                        SeatBean bean=seatData.get(i);
                        if(bean.getId()!=seatBean.getId() && seatBean.isStateGet()){
                            seatData.add(seatBean);
                            break;
                        }else if(bean.getId()==seatBean.getId()){
                            seatData.remove(bean);
                        }
                    }
                }else{
                    if(seatBean.isStateGet()){
                        seatData.add(seatBean);
                    }
                }
                result.confirm();//这里必须调用，否则页面会阻塞造成假死
                setDataView();
                return true;
            }
        });
        //测试链接
//        urlGet = "http://test.h5.opentickets.cn/svgseattest.html?id=101212&goodsPlanId=103043";
        Log.e("urlGet",urlGet);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                webSeat.loadUrl(urlGet);
            }
        },100);
        //加载视频展示的内核兼容
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//            webSeat.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
//        }
        //找到Html文件，也可以用网络上的文件
//        webSeat.addJavascriptInterface(new JavaScriptInterface1(), "console");
    }

    /**
     * 选座展示接口参数拼接
     *
     * @return
     */
    private String getStringParams() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("id=");
        stringBuffer.append(planBean.getGoodsId() + "&");
        stringBuffer.append("goodsPlanId=");
        stringBuffer.append(planBean.getId());
//        stringBuffer.append("&source=android");
        return stringBuffer.toString();
    }

    @OnClick({R.id.ticket_lay, R.id.choice_seat_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ticket_lay://选座信息弹出框
                if(seatData.size()>0){
                    new PopupWindowView(this,seatData,webSeat,this).showUp2(ticketLay);
                }
                break;
            case R.id.choice_seat_button://确定选票的信息
                if(seatData.size()>0){
                    JSONObject jsonObject = new JSONObject();
                    try{
                        for(int i=0;i<seatData.size();i++){
                            SeatBean seatBean=seatData.get(i);
                            jsonObject.put(""+seatBean.getId(), "1");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    if(planBean.getMaxNum()>=seatData.size()){//限制最大购票数
                        getPresenter().getIsOrderCan(ticketBean,planBean,this,jsonObject.toString(),seatData);
                    }else{
                        RxToast.info(String.format(getResources().getString(R.string.ticket_null), planBean.getMaxNum()));
                    }
                }
                break;
        }
    }
    /**
     * 根据数据设置控件显示方式
     */
    private void setDataView(){
        if(seatData.size()>0){//显示控件
            showSize.setVisibility(View.VISIBLE);
            showSize.setText(""+seatData.size());
            float price=0;
            for(SeatBean ticketItem:seatData){
                float get=0;
                get=Float.parseFloat(ticketItem.getPrice());
                price +=get ;
            }
            //float值的四舍五入
            String a=   new DecimalFormat("###,###.##").format(price);
            messageTv.setText(""+a+"元"+"|"+seatData.size()+"张");
        }else{
            showSize.setVisibility(View.GONE);
            messageTv.setText("请点击座位区域选择座位");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webSeat != null) {//清除缓存
            webSeat.stopLoading();
            webSeat.clearHistory();
            webSeat.clearCache(true);
            webSeat.loadUrl("about:blank");
            webSeat.pauseTimers();
            webSeat = null;
        }
    }

    @Override
    public void setOnItemClick(View view, List<SeatBean> pos) {
        seatData=pos;
        if(seatData.size()>0){//显示控件
            showSize.setVisibility(View.VISIBLE);
            showSize.setText(""+seatData.size());
            float price=0;
            for(SeatBean ticketItem:seatData){
                float get=0;
                get=Float.parseFloat(ticketItem.getPrice());
                price +=get ;
            }
            //float值的四舍五入
            String a=   new DecimalFormat("###,###.##").format(price);
            messageTv.setText(""+a+"元"+"|"+seatData.size()+"张");
        }else{
            showSize.setVisibility(View.GONE);
            messageTv.setText("请点击座位区域选择座位");
        }
    }
}
